<template>
  <div>
    <dragWidth v-model:leftWidth="leftWidth" :maxWidth="maxWidth" :minWidth="'20%'">
      <template #left>
        <div class="left-content">
          <div
            class="setting-item"
            :class="{ active: selectIndex === index }"
            v-for="(item, index) in list"
            :key="item.name"
            @click="handleClick(index)"
          >
            {{ item.name }}
          </div>
        </div>
      </template>
      <template #right>
        <div class="right-content">
          <div v-if="selectIndex === 0">
            文件存储位置:
            <el-input
              @focus="handleFocus"
              v-model="list[0].value"
              style="width: 240px"
              placeholder="请输入"
            />
            <el-button type="primary" @click="handleSave">保存</el-button>
          </div>
          <div v-else>是否开启自动备份</div>
        </div>
      </template>
    </dragWidth>
  </div>
</template>

<script lang="ts" setup>
import { useSystemStore } from '@/pinia/system'
const store = useSystemStore()

import { ElMessage } from 'element-plus'
const dragWidth = defineAsyncComponent(() => import('@/components/dragWidth.vue'))
const leftWidth = ref('30%')
const maxWidth = ref('90%')
const list = ref([
  {
    name: '文件存储位置',
    type: 0,
    value: ''
  },
  {
    name: '是否开启自动备份',
    type: 1,
    value: ''
  }
])
const selectIndex = ref(0)
const handleClick = (index: number) => {
  selectIndex.value = index
}
const handleSave = () => {
  if (selectIndex.value === 0) {
    if (!list.value[0].value) {
      ElMessage.warning('请输入文件存储位置')

    }
    store.editstore({
      fileStorage: {
        audioFile: list.value[0].value
      }
    })
    window.electron.ipcRenderer.send('cross-window-message',{
      channel:'useSystemStore',
      data:{
        fileStorage: {
          audioFile: list.value[0].value
        }
      }
    })
  }
}
const isFirstFocus = ref(true) // 添加一个标志位
const handleFocus = async () => {
  if (list.value[0].value.trim() === '' && isFirstFocus.value) {
    isFirstFocus.value = false // 防止重复打开文件选择框
    //打开文件位置
    const filePaths = await window.electron.ipcRenderer.invoke('open-folder')
    if (filePaths) {
      list.value[0].value = filePaths
    } else {
      ElMessage.error('请选择文件存储位置')
    }
    setTimeout(() => {
      isFirstFocus.value = true // 重置标志位
    }, 300) // 等待文件选择框关闭
  }
}
onMounted(() => {
  if (store.fileStorage.audioFile) {
    list.value[0].value = store.fileStorage.audioFile
  }
})
</script>

<style scoped lang="scss">
.right-content {
  background-color: #f0f0f0;
  height: 100%;
}
.setting-item {
  padding: 10px;
  border-radius: 10px;
  border: 1px solid #eee;
  margin-bottom: 5px;

  cursor: pointer;
  &:hover {
    color: #007bff;
    font-weight: bold;
    transition: all 0.3s ease;
  }
  &.active {
    background-color: #007bff;
    color: #fff;
  }
}
</style>
